package com.liao.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liao.common.constant.order.OrderEnum;
import com.liao.common.entity.member.UserAddressEntity;
import com.liao.common.entity.order.OrderItemEntity;
import com.liao.common.entity.order.OrdersEntity;
import com.liao.common.to.order.OrderTo;
import com.liao.common.utils.PageUtils;
import com.liao.common.utils.Query;
import com.liao.common.utils.Result;
import com.liao.common.vo.member.CartDetailVo;
import com.liao.common.vo.order.OrderPreVo;
import com.liao.common.vo.order.OrderSaveReq;
import com.liao.common.vo.order.ProductPreVo;
import com.liao.order.dao.OrdersDao;
import com.liao.order.feign.MemberFeignService;
import com.liao.order.feign.ProductFeignService;
import com.liao.order.service.OrderItemService;
import com.liao.order.service.OrdersService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, OrdersEntity> implements OrdersService {

    @Autowired
    OrdersService ordersService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrdersEntity> page = this.page(
                new Query<OrdersEntity>().getPage(params),
                new QueryWrapper<OrdersEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void add(OrderSaveReq orderSaveReq) {
        OrdersEntity order = orderSaveReq.getOrder();
//        设置订单id
        String OrderId = UUID.randomUUID().toString();
        order.setOrderId(OrderId);
        this.save(order);
//为订单项设置id
        for (OrderItemEntity item : orderSaveReq.getOrderItemList()) {
            item.setOrderId(OrderId);
        }

//锁定库存
        Result lock = productFeignService.lock(orderSaveReq.getOrderItemList());
        System.out.println(lock);
        if (lock.getCode() != 200) {
            throw new RuntimeException(lock.getMsg());
        }
//成功后提交订单数据
        orderSaveReq.getOrder().setOrderStatus(OrderEnum.ORDER_STATUS_NOPAYMENT);
        orderItemService.saveBatch(orderSaveReq.getOrderItemList());
//发送消息到交换机队列
        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order);

    }

    @Override
    public OrdersEntity getOrderByOrderId(String orderId) {
        OrdersEntity orders = baseMapper.selectOne(new QueryWrapper<OrdersEntity>().eq("order_id", orderId));
        return orders;
    }

    @Override
    public void closeOrder(OrdersEntity order) {
        OrdersEntity ordersEntity = getOne(new QueryWrapper<OrdersEntity>().eq("order_id", order.getOrderId()));

        //如果订单是创建未支付的才可以关闭
        if (OrderEnum.ORDER_STATUS_NOPAYMENT == ordersEntity.getOrderStatus()) {
            ordersEntity.setOrderStatus(OrderEnum.ORDER_STATUS_CANCLED);
            ordersService.updateById(ordersEntity);

            try {
                // 发送消息给MQ
                OrderTo orderTO = new OrderTo();
                BeanUtils.copyProperties(ordersEntity, orderTO);
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTO);
            } catch (Exception e) {
                log.error("取消订单，发送mq消息通知解锁库存失败");
            }
        }
    }

    @Override
    public void payOrder(String orderId) {
        OrdersEntity ordersEntity = getOne(new QueryWrapper<OrdersEntity>().eq("order_id", orderId));
        if (ordersEntity.getOrderStatus() == OrderEnum.ORDER_STATUS_NOPAYMENT) {
            ordersEntity.setOrderStatus(OrderEnum.ORDER_STATUS_PAYED);
        }
        throw new RuntimeException("已经支付或订单已经修改");

    }

    @Override
    public OrderPreVo getCartOrder() {

        OrderPreVo orderPreVo = new OrderPreVo();

//        1.获取用户地址信息
        Result<List<UserAddressEntity>> addressListResult = memberFeignService.addressList();
        List<UserAddressEntity> addressListResultData = addressListResult.getData();

        /**
         * 获取用户的默认地址
         */
        for (UserAddressEntity userAddressEntity : addressListResultData) {
            if (userAddressEntity.getIsDefault() == 1) {
                orderPreVo.setUserAddressEntity(userAddressEntity);
                break;
            }
        }


        Result<List<CartDetailVo>> result = memberFeignService.getCart();
        List<CartDetailVo> cartList = result.getData();
//        2.获取用户购物车信息
        for (CartDetailVo cart : cartList) {

            if (cart.getSelected() == 0) {
                continue;
            }
            //获取选择的购物车商品
            ProductPreVo productPreVo = new ProductPreVo();
            BeanUtils.copyProperties(cart, productPreVo);
            orderPreVo.getItemList().add(productPreVo);
        }


        //        3.计算价格

        orderPreVo.setTotalPrice(orderPreVo.getItemList().stream().map(item -> item.getPrice().multiply(new BigDecimal(item.getCount()))).reduce(BigDecimal.ZERO, BigDecimal::add));

        return orderPreVo;
    }


}